import 'dart:async';

import 'package:boss/textStyle/text_style.dart';
import 'package:hi_common/hi_common.dart';
import 'package:flutter/material.dart';

enum TimerType {
  h_m,
  m_s,
}

class TimerText extends StatefulWidget {
  final String dateTime;
  final Duration duration;
  final String title;
  final EdgeInsets margin;
  final TimerType timerType;

  const TimerText({
    Key key,
    this.dateTime,
    this.duration,
    this.title,
    this.margin,
    this.timerType = TimerType.m_s,
  }) : super(key: key);

  @override
  _TimerTextState createState() => _TimerTextState();
}

class _TimerTextState extends State<TimerText> {
  Timer timer;
  DateTime startTime;
  DateTime makeTime;

  String get text {
    var now = DateTime.now();
    if (now.isAfter(makeTime)) {
      return '00:00';
    }

    var leftTime = makeTime.difference(now);

    if (widget.timerType == TimerType.h_m) {
      var hours = leftTime.inHours;
      var minutes = leftTime.inMinutes % 60;

      return '${StringUtil.singlePadLeftZero('$hours')}:${StringUtil.singlePadLeftZero('$minutes')}';
    }

    var minutes = leftTime.inMinutes;
    var seconds = leftTime.inSeconds % 60;

    return '${StringUtil.singlePadLeftZero('$minutes')}:${StringUtil.singlePadLeftZero('$seconds')}';
  }

  @override
  void initState() {
    super.initState();

    startTime = DateTime.parse(widget.dateTime);

    makeTime = startTime.add(widget.duration);

    if (DateTime.now().isBefore(makeTime)) {
      timer = Timer.periodic(Duration(seconds: widget.timerType == TimerType.h_m ? 60 : 1), (timer) {
        if (text == '00:00') {
          timer.cancel();
        }
        setState(() {});
      });
    }
  }

  @override
  void dispose() {
    timer?.cancel();
    timer = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: widget.margin,
      height: 45.w,
      alignment: Alignment.centerLeft,
      child: Text(
        '${widget.title}： $text',
        style: TextStyleConstant().normal_1_28,
      ),
    );
  }
}
